package com.yidu.web;

import com.google.gson.Gson;
import com.yidu.web.dao.UserDao;
import com.yidu.web.model.User;
import com.yidu.web.utils.BaseMessage;
import com.yidu.web.utils.SessionTools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    UserDao dao = new UserDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        /**
         * 获取用户名和密码,然后到数据库查询是否正确
         */
        String userName = request.getParameter("userAccount");
        String userPwd = request.getParameter("userPassword");

        BaseMessage bm = new BaseMessage();

        //dao
        User user = dao.selectByLogin(userName,userPwd);
        if(user!=null){
            request.getSession().setAttribute("user",user);

            bm.setMessage("登录成功!");
            bm.setState(1);
        }else{
            bm.setMessage("用户名或者密码错误!");
            bm.setState(0);
        }
        SessionTools.writerJson(response,bm);
    }
}
